/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.commons.marshaller.decls;

import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.geoscheduler.model.Location;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * JSON field holding Location instance.
 *
 * @author srakyi
 */
public class JSONLocationField extends JSONAbstractFieldDecl<Location> {

	public JSONLocationField(PropertyDescriptor<Location> desc) {
		super(desc);
	}

	public JSONLocationField(PropertyDescriptor<Location> desc, Location defValue) {
		super(desc, defValue);
	}

	/**
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#marshall(org.geoscheduler.commons.marshaller.JSONMarshaller, java.lang.Object, org.json.JSONObject)
	 */
	public JSONObject marshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		PropertyDescriptor<Location> desc = getDescriptor();

		Location valueInst = desc.getValue(instance);
		if (valueInst == null) {
			obj.put(desc.getName(), JSONObject.NULL);
		} else {
			obj.put(desc.getName(), marshaller.marshall(valueInst, new JSONObject()));
		}
		return obj;
	}

	/**
	 * TODO not tested anywhere (yet)
	 * 
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#unmarshall(org.geoscheduler.commons.marshaller.JSONMarshaller, java.lang.Object, org.json.JSONObject)
	 */
	public Object unmarshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		PropertyDescriptor<Location> desc = getDescriptor();
		desc.setValue(instance, (Location)marshaller.unmarshall(new Location(), obj.getJSONObject(desc.getName())));

		return instance;
	}

	public static class Factory extends BaseAbstractFactory<Location> {

		public JSONFieldDecl<Location> create(PropertyDescriptor<Location> desc, JSONMarshaller marshaller) {
			return new JSONLocationField(desc);
		}

		public boolean isApplicable(PropertyDescriptor<?> desc) {
			return super.isApplicable(desc) && Location.class.isAssignableFrom(desc.getType());
		}

	}
}
